# -*- coding: utf-8 -*-
from app import db, app
from hashlib import md5
import flask.ext.whooshalchemy as whooshalchemy


__author__ = 'nibo'

ROLE_USER = 0
ROLE_ADMIN = 1

# 用户关注中间表
followers = db.Table('followers',
                     db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
                     db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
                     )


class User(db.Model):
    """
    用户
    """
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password = db.Column(db.String(64))
    role = db.Column(db.SmallInteger, default=ROLE_USER)
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime)
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    followed = db.relationship('User',
                               secondary=followers,
                               primaryjoin=(followers.c.follower_id == id),
                               secondaryjoin=(followers.c.followed_id == id),
                               backref=db.backref('followers', lazy='dynamic'),
                               lazy='dynamic'
                               )

    def follow(self, user):
        """
        关注用户
        :param user:
        :return:
        """
        if not self.is_following(user):
            self.followed.append(user)
            return self

    def unfollow(self, user):
        """
        取消关注
        :param user:
        :return:
        """
        if self.is_following(user):
            self.followed.remove(user)
            return self

    def is_following(self, user):
        """
        当前用户是否已经关注
        :param user: 用户
        :return:true 已关注,false 未关注
        """
        return self.followed.filter(followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        """
        查询关注用户的所有微博信息
        :return:
        """
        return Post.query.join(followers, (followers.c.followed_id == Post.user_id)).filter(
            followers.c.follower_id == self.id).order_by(Post.timestamp.desc())

    def avatar(self, size=64):
        return 'http://s.gravatar.com/avatar/%s?s=%s&d=mm' % (md5(self.email).hexdigest(), size)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return '<User %s>' % self.nickname


class Post(db.Model):
    """
    微博
    """
    # 索引微博内容字段
    __searchable__ = ['body']

    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Post %s>' % self.body

# 建立索引
whooshalchemy.whoosh_index(app, Post)
